package com.mastercard.assets.web.struts.actions;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mastercard.assets.MasterCardException;
import com.mastercard.assets.jpa.TblAgencia;
import com.mastercard.assets.jpa.TblPaises;
import com.mastercard.assets.util.MCUtil;
import com.mastercard.assets.util.dao.MasterCardDAO;
import com.mastercard.assets.web.struts.forms.CatalogoNuevoItemForm;
import com.mastercard.assets.web.struts.forms.LoginForm;
import com.mastercard.assets.web.util.to.UserLogin;
import com.mastercard.assets.web.util.to.UserTO;
import java.util.List;

public class CrearUsuarioMostrarNiveles
	extends
		Action
{
	public ActionForward execute(
							ActionMapping mapping , 
							ActionForm form ,
							HttpServletRequest request , 
							HttpServletResponse response )
		throws 
			IOException , 
			ServletException
	{
		HttpSession session = request.getSession( ) ;
		
		// en caos de null
		if( session == null )
			return mapping.findForward( "noLogin" ) ;
		
		// toma el userLogin
		UserLogin user = ( UserLogin ) session.getAttribute( "UserLogin" ) ;
		
		// en caso de null
		if( user == null )
			return mapping.findForward( "noLogin" ) ;
		
		// cambia el form
		CatalogoNuevoItemForm f = ( CatalogoNuevoItemForm ) form ;
                String email = f.getCampo2( );
                String login = f.getCampo1( );
                String pass = f.getCampo4( );
                String name = f.getCampo3( );
                int cvePais = f.getCampoInt1( );
		TblPaises pais = MasterCardDAO.getPaisesByCve(cvePais);
		// crea un userTO
		UserTO to = new UserTO( ) ;
		
		//coloca los valores
		to.setLogin( login ) ;
		to.setPass( pass ) ;
		to.setName( name ) ;
		to.setEmail( email ) ;
		to.setPais( pais ) ;
		to.setRolesId( f.getCampoIntArr1( ) ) ;
		
		// consigue los roles
		to.loadRoles( ) ;
		
		// guarda en el UserLogin
		user.setNewUser( to ) ;
                                		
		// en caso de que se cumpla, guarda el WorkArea
		user.setNextWorkArea( "/WEB-INF/pages/WorkArea/CrearUsuarioMostrarNiveles.jsp" ) ;
		
		user.clearMessageError( ) ;
                MasterCardDAO.closeEntityManager( ) ;
	  	return mapping.findForward( "success" ) ;
	}
	
}
